import os
import re
import time
import json
from lxml import etree
from setting import *
from tools import *

def load_state():
    """加载模型调用状态"""
    if os.path.exists(STATE_FILE):
        with open(STATE_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    else:
        return {
            "current_index": 0,
            "usage_counts": {model: 0 for model in MODEL_LIST}
        }


def save_state(state):
    """保存模型调用状态"""
    with open(STATE_FILE, "w", encoding="utf-8") as f:
        json.dump(state, f, indent=2)


def get_next_model():
    """返回当前可用模型，记录一次调用，必要时切换到下一个模型"""
    state = load_state()
    idx = state["current_index"]
    usage = state["usage_counts"]

    while idx < len(MODEL_LIST):
        model = MODEL_LIST[idx]
        if usage[model] < MAX_CALLS_PER_MODEL:
            usage[model] += 1
            break
        else:
            idx += 1  # 当前模型已达上限，尝试下一个模型

    if idx >= len(MODEL_LIST):
        raise Exception("所有模型调用次数都已达上限！")

    # 更新状态并保存
    state["current_index"] = idx
    state["usage_counts"] = usage
    save_state(state)
    return model


def GPT_promote(text):
    completion = client.chat.completions.create(
        # 模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
        model=f"{get_next_model()}",
        messages=[
            {
                "role": "system",
                "content": CONTENT
            },
            {
               "role": "user",
               "content": f"{text}"
            },
        ],

        extra_body={"enable_thinking": False, },# 深度思考:关闭（False）
        stream=True
        # Qwen3模型通过enable_thinking参数控制思考过程（开源版默认True，商业版默认False）
        # 使用Qwen3开源版模型时，若未启用流式输出，请将下行取消注释，否则会报错
        # extra_body={"enable_thinking": False},
    )

    full_text = ""
    for chunk in completion:
        delta = chunk.choices[0].delta
        if hasattr(delta, "content") and delta.content:
            full_text += delta.content

    return full_text



 
if __name__ == '__main__':
    t = GPT_promote("京东此款目前活动售价249元，下单参与满249元减60元优惠活动，国补85折，到手160.65元，近期好价，感兴趣的值友可以入手。")
    print(t)


